package titt.io.encoding.array;

import java.io.ByteArrayOutputStream;
import java.lang.reflect.Array;

import titt.io.encoding.Encoder;
import titt.type.Type;
import titt.type.Types;
import titt.util.Bytes;

public class ArrayEncoder implements Encoder {
	
	private final Encoder non_array;
	
	public ArrayEncoder(Encoder non_array) {
		this.non_array = non_array;
	}
	
	@Override
	public byte[] encode(Type t, Object o) {
		if(t.isArray()) {
			if(o == null) return Bytes.asBytes(Types.NULL_TOKEN);
			
			try {				
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				
				out.write(Types.ARRAY_START);
				
				for(int i = 0; i < Array.getLength(o); i++) {
					if(i > 0) out.write(Types.ARRAY_SPLITTER);
					out.write(encode(t.subtype(), Array.get(o, i)));
				}
				
				out.write(Types.ARRAY_END);

				return out.toByteArray();
			}
			catch(Exception e) {}
		}
		return non_array.encode(t, o);
	}

	@Override
	public boolean isEncodeable(Type t) {
		return (t.isArray() && isEncodeable(t.subtype())) || non_array.isEncodeable(t);
	}

}
